package xutils

import (
	"encoding/json"
	"fmt"
	"gitee.com/xiedongji/antgo/core"
	"strings"

	"github.com/gin-gonic/gin"
)

/* ====================================================================== *
 * 功能:Gin 响应函数封装
 * ====================================================================== */
// 定义错误编码
const (
	CodeSuccess = 0
	CodeError   = 1
	CodeUnLogin = 2
)

type Response struct {
	ErrorCode int         `json:"code"`
	Msg       string      `json:"message"`
	Data      interface{} `json:"data"`
	TraceId   interface{} `json:"trace_id"`
	Stack     interface{} `json:"stack"`
}

func ResponseSuccess(ctx *gin.Context, data interface{}) {
	// 获取链路追踪 变量
	trace, _ := ctx.Get(core.CTX_TRACE)
	traceCtx, _ := trace.(*core.TraceContext)
	traceId := ""
	if traceCtx != nil {
		traceId = traceCtx.TraceId
	}
	// 响应内容
	resp := &Response{ErrorCode: CodeSuccess, Msg: "success", Data: data, TraceId: traceId}
	ctx.JSON(200, resp)

	// 设置 response 变量 用于日志记录RequestLogMiddleware中间件中获取
	respJson, _ := json.Marshal(resp)
	ctx.Set(core.CTX_RESPONSE, string(respJson))
}

func ResponseError(ctx *gin.Context, err error) {
	ResponseErrorCode(ctx, CodeError, err)
}

func ResponseErrorCode(ctx *gin.Context, errCode int, err error) {
	// 获取链路追踪 变量
	trace, _ := ctx.Get(core.CTX_TRACE)
	traceCtx, _ := trace.(*core.TraceContext)
	traceId := ""
	if traceCtx != nil {
		traceId = traceCtx.TraceId
	}

	// 开发模式 显示 堆栈信息
	stack := ""
	if core.RunEnv == core.DevEnv {
		stack = strings.Replace(fmt.Sprintf("%+v", err), err.Error()+"\n", "", -1)
	}

	resp := &Response{ErrorCode: errCode, Msg: err.Error(), Data: "", TraceId: traceId, Stack: stack}
	ctx.JSON(200, resp)

	// 设置 response 变量 用于日志记录RequestLogMiddleware中间件中获取
	respJson, _ := json.Marshal(resp)
	ctx.Set(core.CTX_RESPONSE, string(respJson))
	//ctx.AbortWithError(200, err)
}
